package com.yutel.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseInfoTest {

	public static void main(String[] args) {
		Connection conn = DBHelper.getConn();
		info(conn, "aaa");
		
	}

	public static void info(Connection conn, String tableName) {
		try {
			List<Column> lsColumns = new ArrayList<Column>(10);
			PreparedStatement stmt = conn.prepareStatement("select *  from "
					+ tableName + " where 1=0 ");

			ResultSet resultSet = stmt.executeQuery();
			ResultSetMetaData rsmd = resultSet.getMetaData();
			int n = rsmd.getColumnCount();
			for (int i = 1; i <= n; i++) {
				String colName = rsmd.getColumnName(i);
				// String fieldName = StringUtil.toBeanPatternStr(colName);
				Column column = new Column();
				column.setName(colName);
				column.setJavaName(colName);
				column.setDataType(rsmd.getColumnClassName(i));
				column.setPrecision(String.valueOf(rsmd.getPrecision(i)));
				column.setScale(String.valueOf(rsmd.getScale(i)));
				column.setLength(String.valueOf(rsmd.getColumnDisplaySize(i)));
				column.setNullable(String.valueOf("1".equals(rsmd.isNullable(i))));
				// 获取列注释
				DatabaseMetaData dbmd = conn.getMetaData();
				ResultSet rs = dbmd.getColumns(null, null, tableName, null);
				while (rs.next()) {
					if (colName.equals(rs.getString("COLUMN_NAME")))
						column.setComments(rs.getString("REMARKS"));
				}
				// 获取主键列
				ResultSet rs2 = dbmd.getPrimaryKeys(null, null, tableName);
				while (rs2.next()) {
					if (colName.equals(rs2.getString("COLUMN_NAME")))
						column.setColumnKey("TRUE");
				}
				lsColumns.add(column);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
